package org.mx.service.server.jmx;

import java.lang.management.ManagementFactory;

import javax.management.MBeanServer;
import javax.management.ObjectName;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;

/**
 * mx-service-util相关的JMX MXBean加载类，便于后续进行JMX监控。
 * @author john.peng
 *
 */
public class ServiceMXBeanLoader implements InitializingBean {
	private static final Logger logger = LoggerFactory.getLogger(ServiceMXBeanLoader.class);

	@Value("${web.enabled:false}")
	private boolean webEnabled;
	@Value("${restful.enabled:false}")
	private boolean restEnabled;
	@Value("${servlet.enabled:false}")
	private boolean servletEnabled;
	@Value("${websocket.enabled:false}")
	private boolean websocketEnabled;
	@Value("${tcp.enabled:false}")
	private boolean tcpEnabled;
	@Value("${udp.enabled:false}")
	private boolean udpEnabled;

	private ApplicationContext context = null;

	/**
	 * 构造函数
	 * @param context Spring IoC容器上下文
	 */
	public ServiceMXBeanLoader(ApplicationContext context) {
		super();
		this.context = context;
	}

	private void registryBean(MBeanServer server, String beanName, Class<?> clazz) {
		try {
			Object bean = context.getBean(beanName, clazz);
			if (bean != null) {
				ObjectName webServerName = new ObjectName(String.format("org.mx.server:type=%s", beanName));
				server.registerMBean(bean, webServerName);
				if (logger.isInfoEnabled()) {
					logger.info(String.format("Load the MXBean[%s] success.", beanName));
				}
			} else {
				if (logger.isWarnEnabled()) {
					logger.warn(String.format("The MXBean[%s] not found.", beanName));
				}
			}
		} catch (Exception ex) {
			if (logger.isErrorEnabled()) {
				logger.error(String.format("Load the MXBean[%s] fail.", beanName), ex);
			}
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		MBeanServer server = ManagementFactory.getPlatformMBeanServer();
		// 根据配置需要加载MXBean
		if (tcpEnabled || udpEnabled) {
			registryBean(server, "commServerMXBean", CommServer.class);
		}
		if (webEnabled) {
			registryBean(server, "webServerMXBean", WebServer.class);
		}
		if (websocketEnabled) {
			registryBean(server, "websocketServerMXBean", WebsocketServer.class);
		}
		if (restEnabled) {
			registryBean(server, "restfulServerMXBean", RestfulServer.class);
		}
		if (servletEnabled) {
			registryBean(server, "servletServerMXBean", ServletServer.class);
		}
	}

}
